package com.mulanweb.handler.wechat;

import com.mulanweb.api.module.model.Token;
import com.mulanweb.db.common.Constant;
import com.mulanweb.handler.PostHandler;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/16.
 */
public class TokenHandler{

    public synchronized static  String getAccessToken(){
        Token accessToken = Token.dao.findById(1) ;
        if(accessToken !=null ){
            return accessToken.getValue() ;
        }
        return null ;
    }

    public synchronized static String refreshAccessToken(){
        Map<String,String> para = PostHandler.post(Constant.WeChatFinalValue.getGetAccessTokenUrl());
        if(para.containsKey("errcode")){
            System.out.println("错误消息："+para.get("errorCN"));
        }else {
            if(para.containsKey("access_token")){
                Token accessToken = Token.dao.findById(1);
                if(accessToken != null){
                    accessToken.setValue(para.get("access_token"));
                    Calendar today = Calendar.getInstance();
                    today.setTime(new Date());
                    Date createTime = accessToken.getCreateTime();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(createTime);
                    if((calendar.getWeekYear()) == today.getWeekYear()
                            && calendar.get(Calendar.MONTH) == today.get(Calendar.MONTH)
                            &&  calendar.get(Calendar.DATE) == today.get(Calendar.DATE)){
                        accessToken.setTodayCount(accessToken.getTodayCount()+1);
                    }else{
                        accessToken.setTodayCount(1);
                    }
                    accessToken.setCreateTime(new Date());
                    if (accessToken.update()) {
                        System.out.println("-------------------access_token刷新成功");
                        return accessToken.getValue() ;
                    }
                }else{
                    accessToken = new Token();
                    accessToken.setValue(para.get("access_token"));
                    accessToken.setTodayCount(1);
                    accessToken.setCreateTime(new Date());
                    if(accessToken.save()){
                        System.out.println("-------------------access_token保存成功");
                        return accessToken.getValue() ;
                    }
                }
            }
        }
          return null ;
    }
}
